﻿using System;
using System.Web.UI.WebControls;
using SistemaCarros.Entidades;

namespace SistemaCarros.Paginas
{
    public partial class ListaCarros : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            try
            {
                if (!Page.IsPostBack)
                    carregarCarros();
            }
            catch (Exception ex)
            {
                Session.Add("erro", ex);
                Response.Redirect("PaginaErro.aspx", false);
            }
        }
        protected void grdLista_PageIndexChanging(object sender, GridViewPageEventArgs e)
        {
            try
            {
                grdLista.PageIndex = e.NewPageIndex;
                grdLista.DataSource = ViewState["carros"];
                grdLista.DataBind();

            }
            catch (Exception ex)
            {
                Session.Add("erro", ex);
                Response.Redirect("PaginaErro.aspx", false);
            }
        }
        protected void btnNovo_Click(object sender, EventArgs e)
        {
            Response.Redirect("InserirCarro.aspx", false);
        }
        protected void btnEditar_Click(object sender, EventArgs e)
        {
            try
            {
                int id = Convert.ToInt32((sender as Button).Attributes["ItemSelecionado"]);
                ViewState.Add("id", id);
                Response.Redirect("EditarCarro.aspx?id=" + id, false);
            }
            catch (Exception ex)
            {
                Session.Add("erro", ex);
                Response.Redirect("PaginaErro.aspx", false);
            }
        }
        protected void btnExcluir_Click(object sender, EventArgs e)
        {
            try
            {
                int id = Convert.ToInt32((sender as Button).Attributes["ItemSelecionado"]);
                excluirCarro(id);
            }
            catch (Exception ex)
            {
                Session.Add("erro", ex);
                Response.Redirect("PaginaErro.aspx", false);
            }

        }

        private void carregarCarros()
        {
            ViewState.Add("carros", new Carro().Carregar());
            grdLista.DataSource = ViewState["carros"];
            grdLista.DataBind();
        }
        private void excluirCarro(int id)
        {
            Carro objCarro = new Carro();
            objCarro.Id = id;

            objCarro.Excluir();

            carregarCarros();
        }
    }
}